package orderCus;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.Cart;
import common.Customer;
import common.Item;

public class OrderRegistServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		//ログインチェック
		HttpSession session = req.getSession();
		Customer user = (Customer)session.getAttribute("user");
		if(user == null || user.equals("null")) resp.sendRedirect(req.getContextPath() +"/index.jsp");
		else
		{
			req.setCharacterEncoding("UTF-8");
			String msg = null;
			String name =  new String (req.getParameter("in").getBytes("UTF-8"));		//商品名
			String category = req.getParameter("cg");		//カテゴリーコード
			String code = req.getParameter("code");		//商品コード
			Cart cart = (Cart)session.getAttribute("cart");		//カート
			String strOrders = req.getParameter("orders");			//注文数
			Item item = Item.find_by_code(code);
			int orders = 0;
			try
			{
				 orders = Integer.parseInt(strOrders);
				 if(orders > item.getStock())
				 {
					 msg = "注文数が在庫数を上回っています。";
				 }
			}
			catch(NumberFormatException e)
			{
				msg = ("個数を半角数字で入力してください。");
			}
			
			if(msg == null || msg.length() == 0)
			{
				cart.add(code, orders);
				session.setAttribute("cart", cart);
	//					item.setStock(orders);
				msg = "カートに追加しました";
			}
			req.setAttribute("msg", msg.toString());
			req.setAttribute("in", name);
			req.setAttribute("cg", category);
			RequestDispatcher dispatcher = req.getRequestDispatcher("../customer/itemList.jsp");
			dispatcher.forward(req, resp);
		}
	}
}
